<?php

namespace App\Winged\Seeds;

use Encore\Admin\Auth\Database\Role;
use Illuminate\Database\Seeder;
use Encore\Admin\Auth\Database\Menu;
use Illuminate\Support\Facades\DB;

class WingedBaseSeeder extends Seeder
{

    protected $config ;

    public function init()
    {
        $this->createRole();
        $this->setMenu();
    }

    private function createRole()
    {
        $role = $this->config['roles'] ?? null ;
        $role && Role::insert($role);
    }
    /*
     * 创建一个新菜单，如果该菜单已存在，则对其进行更新。
     * @param $parentMenuId 上级菜单的id，默认为0（顶层菜单）
     */
    protected function setMenu()
    {
        $menu = $this->config ['menu'] ?? [] ;
        collect($menu)->map(function($item){
            $this->createMenu($item);
        });
    }

    private function createMenu($item ,$parent_id = null)
    {
        $menu = new Menu();
        $menu->order = $item['order'];
        $menu->uri = $item['uri'];
        $menu->icon = $item ['icon'];
        $menu->service = $item['service'];
        if(! is_null($parent_id)){
            $menu->parent_id = $parent_id;
        }else{
            $menu->parent_id = $item['parent_id'];
        }
        $menu->title = $item ['title'];
        $menu->save();
        if(isset($item['roles'])){
            foreach($item ['roles'] as $role){
                $menu->roles()->save(Role::where(['slug' => $role])->first());
            }
        }
        if(array_key_exists('sub_menu',$item) && !empty($item['sub_menu'])){
            $sub = $item ['sub_menu'];
            foreach($sub as $key => $val){
                $this->createMenu($val , $menu->id);
            }
        }

    }
}
